import 'package:flutter/widgets.dart';
import 'package:library_base/entities/distribution_child_entity.dart';
import 'package:library_base/entities/enum_entity.dart';
import 'package:library_base/entities/event/dispatcher_goods_count.dart';
import 'package:library_base/event/event.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:get/get.dart';
import 'package:library_base/provider/base_list_controller.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/channel.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:library_base/entities/stock_out_entity.dart';
import 'package:library_base/entities/stock_out_child_entity.dart';

class AsOrderController extends BaseListController<StockOutEntity, StockOutChildEntity> {
  String stationTimeBegin = '';

  Rx<String> keyWord = ''.obs;

  Rx<bool> isConnected = false.obs;

  double finishedCount = 0.0;

  double totalCount = 0.0;

  bool enable = false;

  RxList<String> stockOutIds = <String>[].obs;

  ///是否全选
  bool isSelectedAll = false;

  TextEditingController keyWorkSearchController = TextEditingController();

  @override
  void onCreate() {
    enableLoadMore = true;
    isShowNoMoreFooter = true;
  }

  @override
  Future requestData() {
    isFirstLoading = true;
    requestGeneralListData(Apis.STOCK_OUT_PAGE,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "pageNo": page,
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
    return super.requestData();
  }

  @override
  List<StockOutChildEntity> transformObject(
      StockOutEntity data, bool isRefresh) {
    if (isRefresh) {
      stockOutIds.clear();
    }
    return data.list;
  }

  @override
  void loadAfter() {
    if(isFirstLoading){
      stockOutIds.clear();
    }
    var finishedList = listData.where((p0) => p0.status == StockOutOrderStatus.FINISHED.name).toList();
    isSelectedAll = stockOutIds.length == finishedList.length && finishedList.isNotEmpty;
    enable = stockOutIds.isNotEmpty;
    Event.eventBus.fire(DispatcherGoodsCount(0, listData.length));
  }

  void filter(String time) {
    stationTimeBegin = time;
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.STOCK_OUT_PAGE,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "pageNo": getPage(false),
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "stationTimeEnd": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
  }

  @override
  Future onRefreshCallback() async {
    requestGeneralListData(
        Apis.STOCK_OUT_PAGE,
        isRefresh: true,
        method: FBResultFul.GET,
        isShowErrorToastTip:false,
        queryParameters: {
          "pageNo": getPage(true),
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "stationTimeEnd": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
  }

  @override
  Future onLoadCallback() async {
    requestGeneralListData(Apis.STOCK_OUT_PAGE,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "pageNo": getPage(false),
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "stationTimeEnd": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
  }

  void onSearch(String value) {
    tryReLoad();
  }

  void onChanged(String value) {
    if (keyWord.value != value) {
      keyWord.value = value;
      update();
    }
  }

  void backToList() {
    keyWord.value = '';
    keyWorkSearchController.text = '';
    stationTimeBegin = '';
    tryReLoad();
  }

  void reset() {
    stationTimeBegin = '';
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.STOCK_OUT_PAGE,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "pageNo": getPage(false),
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "stationTimeEnd": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
  }

  void tryReLoad() {
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.STOCK_OUT_PAGE,
        isRefresh: false,
        method: FBResultFul.GET,
        queryParameters: {
          "pageNo": getPage(false),
          "pageSize": limit,
          "stationTimeBegin": stationTimeBegin,
          "stationTimeEnd": stationTimeBegin,
          "orderNumber": keyWord.value,
        });
  }

  void onItemClick(StockOutChildEntity itemData) {}

  void onExpand(StockOutChildEntity itemData) {}

  void onTapChild(DistributionChildEntity itemData) {}

  void toOrderDetail(StockOutChildEntity itemData, int position) {
    Get.toNamed(Routers.ORDER_DETAIL_PAGE,
        arguments: {'id': itemData.id, 'callback': tryReLoad});
  }

  ///发货
  void deliverGoods() {
    requestUniversal<bool>(Apis.FINISH_RECORDS,
        tipSuccess: MultiLanguage.successfulDelivery.tr,
        isShowToastTip: true,
        params: {"stockOutIds":stockOutIds}, resultSuccessCall: (result) async {
          tryReLoad();
        });
  }

  ///打印
  void print() {
    if(GetPlatform.isAndroid){
      sendAndroidChannel.invokeMethod(CHECK_BLUETOOTH_IS_OPEN_4);
    }else{
      Get.toNamed(Routers.PRINT_DETAIL_PAGE,arguments: {"ids":stockOutIds});
    }
  }

  ///全选
  void selectedAll() {
    var finishedList = listData.where((p0) => p0.status == StockOutOrderStatus.FINISHED.name).toList();
    if(finishedList.isEmpty){
      ToastUtil.normal("列表没有发现已完成的订单,请尝试上拉加载到已完成的订单");
      return;
    }
    bool isCheckAllComplete = finishedList.length == stockOutIds.length;
    stockOutIds.clear();
    for (int i = 0; i < finishedList.length; i++) {
      finishedList[i].isSelected = !isCheckAllComplete;
      if(finishedList[i].isSelected){
        stockOutIds.add(finishedList[i].id);
      }
    }
    loadAfter();
    baseState!.setState(() {});
  }

  ///选中或者取消选中
  void onCheck(StockOutChildEntity taskEntity, int position) {
    taskEntity.isSelected = !taskEntity.isSelected;
    if (stockOutIds.value.contains(taskEntity.id)) {
      stockOutIds.value.remove(taskEntity.id);
    } else {
      stockOutIds.value.add(taskEntity.id);
    }
    loadAfter();
    baseState!.setState(() {});
  }

}

